package com.chezai.client.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chezai.client.R;
import com.chezai.client.bean.ClassRecord;
import com.chezai.client.bean.CoachLoginRecord;
import com.chezai.client.bean.StudentSignInSucessEvent;
import com.chezai.client.bean.TakePhotoEntity;
import com.chezai.client.bean.TrainInfo;
import com.chezai.client.bean.TrainProjectEntity;
import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.manager.ClassRecordDaoManager;
import com.chezai.client.dao.manager.CoachLoginRecordDaoManager;
import com.chezai.client.dao.manager.StudentStudyRecordDaoManager;
import com.chezai.client.dao.manager.TrainProjectEntityManager;
import com.chezai.client.dao.manager.UserInfoDaoManager;
import com.chezai.client.global.Const;
import com.chezai.client.global.location.LocationMgr;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.server.TerminalSocketClientManager_8001;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.BuildDataUtil;
import com.chezai.client.utils.CameraMgr;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.DialogUtils;
import com.chezai.client.utils.LocationUtils;
import com.chezai.client.widget.ListDialog;
import com.jx.driving.transmission.Terminal0x0201Transmission;
import com.jx.driving.transmission.Terminal0x8201Transmission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;


/**
 * 学员信息页
 * Created by likunyang on 2017/9/13.
 */

public class StudentInfoFragment extends BaseFragment implements RadioGroup.OnCheckedChangeListener, ListDialog.OnItemClickListener, View.OnClickListener {

    private static String STUDENT_INFO_ID = "studentInfo_Id";
    private static String COACH_LOGIN_RECORD_ID = "coachLoginRecordId";
    @BindView(R.id.btn_back)
    Button btnBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_student_id_card)
    TextView tvStudentIdCard;
    @BindView(R.id.rb_part_two)
    RadioButton rbPartTwo;
    @BindView(R.id.rb_part_three)
    RadioButton rbPartThree;
    @BindView(R.id.rg_train_part)
    RadioGroup rgTrainPart;
    @BindView(R.id.btn_start_teach)
    Button btnStartTeach;

    private int mTrainPart;
    private UserInfo mStudentInfo;
    private TransmissionMessageUtil messageUtil;
    private TrainProjectEntity mCurrentTrainProject;
    private long coachLoginRecordId;
    private long studentInfoId;
    private long classId;
    private String courseId;
    private UserInfo mCoachInfo;
    private TakePhotoEntity mTakePhoto;
    private Handler mHandler;
    private Runnable btnRunnable;

    public static StudentInfoFragment newInstance(long studentInfoId, long coachLoginRecordId) {
        StudentInfoFragment fragment = new StudentInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putLong(STUDENT_INFO_ID, studentInfoId);
        bundle.putLong(COACH_LOGIN_RECORD_ID, coachLoginRecordId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        DialogUtils.dismissDialog();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_student_info;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mContext = getContext();
        DialogUtils.dismissDialog();
        Bundle bundle = getArguments();
        studentInfoId = bundle.getLong(STUDENT_INFO_ID);
        coachLoginRecordId = bundle.getLong(COACH_LOGIN_RECORD_ID);
        mStudentInfo = UserInfoDaoManager.getInstance().findUserInfoById(studentInfoId);
        CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().findCoachLoginRecord(coachLoginRecordId);
        mCoachInfo = coachLoginRecord.getCoachInfo();
        btnBack.setVisibility(View.GONE);
        tvTitle.setText("学员信息");
        tvStudentIdCard.setText(mStudentInfo.getIDCardNum());
        BuildDataUtil.clearStudentClassId();
    }


    @Override
    public void initData() {
        messageUtil = new TransmissionMessageUtil();
        mHandler = new Handler();
        btnRunnable = new BtnRunnable(btnStartTeach);
    }

    @Override
    public void setListener() {
        rgTrainPart.setOnCheckedChangeListener(this);
        btnStartTeach.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (DeviceUtils.isDoubleClick()) {
            return;
        }
        if (rbPartTwo.isChecked() || rbPartThree.isChecked()) {
            showSelectTrainSubjectDialog();
            btnStartTeach.setEnabled(false);
        } else {
            showToast("请选择培训部分");
        }
    }

    /**
     * 保存课堂数据
     */
    public void saveData() {
        ClassRecord classRecord = new ClassRecord();
        classRecord.setClassId(classId);
        classRecord.setCourseNum(courseId);
        classRecord.setSid(studentInfoId);
        classRecord.setTrainPart(mTrainPart);
        classRecord.setTrainSubject(mCurrentTrainProject.getProjectName());
        Long classRecordId = ClassRecordDaoManager.getInstance().insertClassRecord(classRecord);
        StudentStudyRecordDaoManager.getInstance().insertStudentStudyRecord(coachLoginRecordId, studentInfoId, classRecordId);
        EventBus.getDefault().post(new TrainInfo(classRecordId, mTrainPart == Const.TrainPart.TWO ? "第二部分" : "第三部分"));
    }

    /**
     * 上报学员登录响应
     *
     * @param ox8201
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8201Transmission(Terminal0x8201Transmission ox8201) {
        DialogUtils.dismissDialog();
        //学员登录应答
        short result = ox8201.getResult();
        //登录结果1：登录成功；2：无效的学员编号；3：禁止登录的学员；4：区域外教学提醒；5：准教车型与培训车型不符；9：其他错误
        switch (result) {
            case 1:
                showToast("学员登录成功");
                EventBus.getDefault().post(new StudentSignInSucessEvent(mTakePhoto));
                break;
            case 2:
                showToast("无效的学员编号");
                break;
            case 3:
                showToast("禁止登录的学员");
                break;
            case 4:
                showToast("区域外教学提醒");
                break;
            case 5:
                showToast("准教车型与培训车型不符");
                break;
            case 9:
                //上次学员没有成功退出
                showToast("其他错误");
                break;
        }
    }

    /**
     * 展示选择训练项目弹窗
     */
    private void showSelectTrainSubjectDialog() {
        List<TrainProjectEntity> trainProjectsByPart = TrainProjectEntityManager.getInstance().getTrainProjectsByPart(getContext(), mTrainPart);
        ListDialog listDialog = new ListDialog(getContext());
        listDialog.setData(trainProjectsByPart);
        listDialog.setOnItemClickListener(this);
        listDialog.show();
    }

    /**
     * 选择训练项目 item点击回调
     */
    @Override
    public void onItemClick(Dialog dialog, TrainProjectEntity t) {
        dialog.dismiss();
        DialogUtils.showProgressBarDialog(getContext(), "学员登录中...");
        mCurrentTrainProject = t;
        classId = BuildDataUtil.getStudentClassId();
        BuildDataUtil buildDataUtil = new BuildDataUtil();
        buildDataUtil.setPart(mTrainPart + "");
        buildDataUtil.setProject(mCurrentTrainProject.getProjectCode());
        buildDataUtil.setStudentDrivingType(mStudentInfo.getDrivingType());
        courseId = buildDataUtil.buildCourseId();
        takeStudentSignInPhoto();
    }

    @Override
    public void onCloseClick(Dialog dialog) {
        if (btnStartTeach != null) {
            btnStartTeach.setEnabled(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        mCurrentTrainProject = null;
        switch (checkedId) {
            case R.id.rb_part_two:
                mTrainPart = TrainProjectEntity.TRAIN_PART_TWO;
                break;
            case R.id.rb_part_three:
                mTrainPart = TrainProjectEntity.TRAIN_PART_THREE;
                break;
        }
    }

    /**
     * 上报学员登录
     *
     * @param photoEntity
     */
    public void tell0x0201Transmission(TakePhotoEntity photoEntity) {
        //上报学员登陆
        Terminal0x0201Transmission ox0201 = new Terminal0x0201Transmission();
        ox0201.setUserNo(mStudentInfo.getUnifiedNum());
        ox0201.setCoachNo(mCoachInfo.getUnifiedNum());
        ox0201.setClassId(classId);
        ox0201.setCourse(courseId);
        ox0201.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        //harisucici 上报监管
        TerminalSocketClientManager_8001.getInstance().tellWithNoAuth(messageUtil.buildTerminal0x0900Request(ox0201, false, true));
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0201, false, true));
        this.mTakePhoto = photoEntity;
    }

    /**
     * 学员签到拍照
     */
    public void takeStudentSignInPhoto() {
        DialogUtils.dismissDialog();
        if (mHandler != null) {
            mHandler.postDelayed(btnRunnable, 10 * 1000);
        }
        CameraMgr.startFaceCamera(mContext,
                mStudentInfo.getUnifiedNum(),
                Const.PhotoEventType.STUDENT_SIGN_IN,
                mTrainPart,
                mStudentInfo.getName(),
                mCoachInfo.getName(),
                null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mHandler != null) {
            mHandler.removeCallbacks(btnRunnable);
        }
    }

    static class BtnRunnable implements Runnable {
        private WeakReference<Button> weakBtn;

        public BtnRunnable(Button btn) {
            weakBtn = new WeakReference<>(btn);
        }

        @Override
        public void run() {
            if (weakBtn != null && weakBtn.get() != null) {
                weakBtn.get().setEnabled(true);
            }
        }
    }
}
